<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>移动的盒子</title>
  </head>
  <style>
    * {
      padding: 0px;
      margin: 0px;
    }
    .moveBox {
      width: 200px;
      height: 200px;
      border-radius: 20px;
      margin: 10px auto;
      background-color: skyblue;
      position: absolute;
    }
    .moveBox p {
      text-align: center;
    }
  </style>
  <body>
    <div class="moveBox">
      <p>我是标题</p>
    </div>
  </body>
  <script>
    //   按住我可以拖动
    const moveBox = document.querySelector(".moveBox");
    // 给盒子注册一个点击事件
    moveBox.addEventListener("mousedown", function (e) {
      // 获取到盒子的中间位置
      // console.log((e.pageX = +e.clientX));
      var x = e.pageX;
      var y = e.pageY;
      moveBox.style.left = x - moveBox.clientWidth / 2 + "px";
      moveBox.style.top = y - moveBox.clientHeight / 2 + "px";
      // console.log((e.pageY = moveBox.clientHeight / 2 + e.clientY));
      // 获取到的盒子初始位置
      const boxX = e.pageX - moveBox.offsetLeft;
      const boxY = e.pageY - moveBox.offsetTop;
      //   console.log(e.target);
      document.addEventListener("mousemove", move);
      function move(el) {
        // 获取到的盒子初始位置
        let moveX = el.pageX - boxX + "px";
        let moveY = el.pageY - boxY + "px";
        moveBox.style.left = moveX;
        moveBox.style.top = moveY;
      }
      document.addEventListener("mouseup", function (e) {
        document.removeEventListener("mousemove", move);
      });
    });

    // moveBox.addEventListener("mousedown", function (e) {
    //   var x = e.pageX - moveBox.offsetLeft;
    //   var y = e.pageY - moveBox.offsetTop;

    //   document.addEventListener("mousemove", move);

    //   function move(e1) {
    //     moveBox.style.left = e1.pageX - x + "px";
    //     moveBox.style.top = e1.pageY - y + "px";
    //   }

    //   document.addEventListener("mouseup", function () {
    //     document.removeEventListener("mousemove", move);
    //   });
    // });
    // 去除数组中重复的
  </script>
</html>
